package cc.fs.kotlinproject

import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import cc.fs.kotlinproject.utlis.e
import java.lang.ref.WeakReference
import kotlin.properties.Delegates

/**
 * Created by fostion on 2015/8/14.
 */

public abstract class BaseActivity : AppCompatActivity() {
    companion object {
        private val handlers = arrayListOf<MyHandler>();

        public fun brocast(message : Message){
            for(handler in handlers){
                var msg  = Message()
                msg.copyFrom(message)
                handler.sendMessage(msg)
            }
        }

        public fun addHandler(handler: MyHandler) {
            handlers.add(handler)
        }

        public fun deleteHandler(handler: MyHandler) {
            handlers.remove(handler)
        }

        public fun removeAll(){
            handlers.clear()
        }

    }

    public val mHandler:MyHandler by Delegates.lazy {
        MyHandler(this)
    }

    public val _this:BaseActivity by Delegates.lazy {
        this!!
    }

    abstract fun handler(message : Message)

    public fun sendMessage(message:Message){
        val msg = Message()
        msg.copyFrom(message)
        mHandler.sendMessage(msg)
    }

    public fun runDelay(run:() -> Unit,delayMillis:Long){
        val msg = Message()
        msg.what = -101
        msg.arg1 = -102
        msg.arg2 = -103
        msg.obj = run
        mHandler.sendMessageDelayed(msg,delayMillis)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        addHandler(mHandler)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.getItemId()) {
            android.R.id.home -> this.finish()
        }
        return super.onOptionsItemSelected(item)
    }

    override fun finish() {
        deleteHandler(mHandler)
        e("   "+handlers.size())
        super.finish()
    }

    inner class MyHandler : Handler{
       private val outer:WeakReference<BaseActivity>;

        constructor(activity: BaseActivity){
            outer = WeakReference(activity)
        }

        override fun handleMessage(msg: Message) {
            if(outer.get() == null){
                BaseActivity.deleteHandler(this)
                return
            }
            //rundelay
            if(msg.what == -101 && msg.arg1 == -102 && msg.arg2 == -103){
                (msg.obj as () -> Unit).invoke()
                return
            }
            outer.get().handler(msg)
        }
    }

}

